#include "threadPool.h"
#include <math.h>
#include<mysql/mysql.h>
#include <string.h>

int create_salt(unsigned char*salt) {//创建盐值
    const char charset[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    srand(time(NULL));  // 初始化随机种子（不够安全！）
    strcpy((char*)salt, "$6$");
    for (int i = 3; i < 31; i++) {
        salt[i] = charset[rand() % (sizeof(charset) - 1)];
    }
    salt[31] = '\0';

    printf("salt=%s\n",salt);
    return 0;
}
int create_encrypt(unsigned char*salt,char*password,unsigned char*digest){//创建密文
    unsigned char combined[32+8];
    memcpy(combined, password, 8);
    memcpy(combined + 8, salt, 32);

    // 计算SHA-256哈希
    SHA256(combined, 32+8, digest);


    return 0;
}
int get_user_id(MYSQL *db, const char *username) {
    char query[256];
    MYSQL_RES *result;
    MYSQL_ROW row;
    int user_id = -1;  // 默认返回-1表示未找到

    // 构建查询语句
    snprintf(query, sizeof(query), 
             "SELECT id FROM users WHERE username = '%s' AND isDelete = 0", 
             username);

    // 执行查询
    if (mysql_query(db, query)) {
        fprintf(stderr, "查询失败: %s\n", mysql_error(db));
        return -1;
    }

    // 获取结果集
    result = mysql_store_result(db);
    if (result == NULL) {
        fprintf(stderr, "存储结果失败: %s\n", mysql_error(db));
        return -1;
    }

    // 处理结果
    if ((row = mysql_fetch_row(result)) != NULL) {
        user_id = atoi(row[0]);  // 将字符串形式的ID转为整数
    }

    // 释放结果集
    mysql_free_result(result);

    return user_id;
}

/*
int tackle_register(int socket, MYSQL *db,TLV_t*TLV_RECV){
    int user_id=1;
    TLV_t*TLV_T=(TLV_t*)malloc(sizeof(TLV_t));
    memset(TLV_T,0,sizeof(TLV_t));
    char buf[9];
    char buf1[9];
    char query[256];

    for(int i=0;i<8;i++){
        buf[i]=TLV_RECV->value[i];
        buf1[i]=TLV_RECV->value[i+8];

    }
    buf[8]='\0';
    buf1[8]='\0';
    printf("buf用户名=%s\n buf1密码=%s\n,TLV_RECV->value=%s\n",buf, buf1,TLV_RECV->value);
    snprintf(query, sizeof(query), 
             "SELECT id FROM users WHERE username = '%s' AND isDelete = 0",
             buf);
    if (mysql_query(db, query)) {
        fprintf(stderr, "查询失败: %s\n", mysql_error(db));
        user_id= -1;
    }

    MYSQL_RES *result = mysql_store_result(db);
    if (result == NULL) {
        fprintf(stderr, "存储结果失败: %s\n", mysql_error(db));
        user_id= -1;
    }
    if (mysql_num_rows(result) > 0) {

        printf("用户名已存在\n");
        TLV_T->type=0xFF;
        TLV_T->length=0;
        sendTlv(socket,TLV_T);
        user_id= -2; // 用户名已存在
    }
    unsigned  char salt[32];
    create_salt(salt);
    unsigned char digest[33];
    create_encrypt(salt,buf1,digest);
    snprintf(query, sizeof(query),
             "INSERT INTO users (username, password, saltNum, ciphertext, isLoggedIn) "
             "VALUES ('%s', '%s', '%s', '%s', 0)",//未测试暂时写为0，需改成1
             buf, buf1, salt, digest);

    if (mysql_query(db, query)) {
        fprintf(stderr, "注册失败: %s\n", mysql_error(db));
        user_id= -1;
    }
    else
        user_id=get_user_id(db,buf);

    if(user_id>0){
        printf("用户注册成功\n");
        TLV_T->type=0x30;
        TLV_T->length=0;
        printf("use_id==%d",user_id);   

    }else{
        TLV_T->type=0xff;
        TLV_T->length=0;


    }
    sendTlv(socket,TLV_T);
    free(TLV_T);
    if (result != NULL)mysql_free_result(result);   

    return user_id;

}
*/

int tackle_register(int socket, MYSQL *db, TLV_t *TLV_RECV) {
    int user_id = -1;
    TLV_t* TLV_T = (TLV_t *)malloc(sizeof(TLV_t));
    memset(TLV_T, 0, sizeof(TLV_t));

    // 1. 解析用户名和密码（各8字节）
    char username[9] = {0};
    char password[9] = {0};
    memcpy(username, TLV_RECV->value, 8);
    memcpy(password, TLV_RECV->value + 8, 8);

    // 2. 检查用户名是否已存在
    MYSQL_STMT *stmt = mysql_stmt_init(db);
    const char *query = "SELECT id FROM users WHERE username = ? AND isDelete = 0";
    mysql_stmt_prepare(stmt, query, strlen(query));

    MYSQL_BIND param = {0};
    param.buffer_type = MYSQL_TYPE_STRING;
    param.buffer = username;
    param.buffer_length = 8;
    mysql_stmt_bind_param(stmt, &param);

    if (mysql_stmt_execute(stmt) || mysql_stmt_store_result(stmt)) {
        fprintf(stderr, "查询失败: %s\n", mysql_stmt_error(stmt));
        goto cleanup;
    }

    if (mysql_stmt_num_rows(stmt) > 0) {
        TLV_T->type = 0xFF; // 用户名已存在
        user_id = -2;
        goto cleanup;
    }
    mysql_stmt_close(stmt);

    // 3. 生成盐值和密码哈希
    unsigned char salt[32];
    unsigned char hash[SHA256_DIGEST_LENGTH];
    create_salt(salt);
    create_encrypt(salt, password, hash);

    // 4. 插入新用户（使用预处理语句）
    stmt = mysql_stmt_init(db);
    query = "INSERT INTO users (username, password, saltNum, ciphertext,isLoggedIn) VALUES (?, ?, ?, ?,0)";
    mysql_stmt_prepare(stmt, query, strlen(query));

    MYSQL_BIND params[4] = {0};
    params[0].buffer_type = MYSQL_TYPE_STRING;
    params[0].buffer = username;
    params[0].buffer_length = 8;

    params[1].buffer_type = MYSQL_TYPE_STRING;
    params[1].buffer = password; // 明文密码（实际应只存哈希）
    params[1].buffer_length = 8;

    params[2].buffer_type = MYSQL_TYPE_BLOB;
    params[2].buffer = salt;
    params[2].buffer_length = 32;

    params[3].buffer_type = MYSQL_TYPE_BLOB;
    params[3].buffer = hash;
    params[3].buffer_length = SHA256_DIGEST_LENGTH;

    mysql_stmt_bind_param(stmt, params);
    if (mysql_stmt_execute(stmt)) {
        fprintf(stderr, "注册失败: %s\n", mysql_stmt_error(stmt));
        goto cleanup;
    }

    user_id = mysql_stmt_insert_id(stmt); // 获取新用户ID
    TLV_T->type = 0x30; // 注册成功

cleanup:
    if (user_id <= 0) TLV_T->type = 0xFF;
    sendTlv(socket, TLV_T);
    if (stmt) mysql_stmt_close(stmt);
    free(TLV_T);
    return user_id;
}

